from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QFileDialog, QMessageBox
from PyQt5 import uic
from PyQt5.QtCore import Qt
from ament_index_python.packages import get_package_share_directory
import sys
import json
import os

from trace_visualizer_py.debug_log import DebugLog
from trace_visualizer_py.usv_ui import Ui_MainWindow
from trace_visualizer_py.common import common_data


# class MainWindow(QMainWindow, Ui_MainWindow):
class MainWindow(QMainWindow, uic.loadUiType("/home/ajream/quickDir/rosStudy/ros2qtws/src/trace_visualizer_py/resource/usv_ui.ui")[0]):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 重定向 print 输出到 textEdit_Debug
        sys.stdout = DebugLog(self.textEdit_Debug)

        common_data['cfg_basic'].config_changed.connect(self.on_config_changed)  # 连接信号

        self.actionSaveCfg.triggered.connect(self.save_config)
        self.actionLoadCfg.triggered.connect(self.load_config)

        self.layout = QHBoxLayout()
        self.draw_widget.setLayout(self.layout)
        
        self.layout.addWidget(common_data['widget_trace'])

        self.groupBox_Debug.layout().addWidget(common_data['gl_widget'])


        self.textEdit_Debug.setReadOnly(True)  # 禁止用户输入
        self.textEdit_Debug.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)  # 确保滚动条始终可见


        # UI事件处理
        self.spinBox_PoolWidth.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_PoolWidth_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_PoolLength.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_PoolLength_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_UWB1_X.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_UWB1_X_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_UWB1_Y.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_UWB1_Y_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_UWB2_X.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_UWB2_X_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_UWB2_Y.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_UWB2_Y_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_UWB3_X.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_UWB3_X_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_UWB3_Y.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_UWB3_Y_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_PID_P.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_PID_P_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_PID_I.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_PID_I_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_PID_D.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_PID_D_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_PID_P_2.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_PID_P_2_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_PID_I_2.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_PID_I_2_ValueChanged(self, common_data['cfg_basic']))
        self.spinBox_PID_D_2.valueChanged.connect(lambda: common_data['handler_ui'].spinBox_PID_D_2_ValueChanged(self, common_data['cfg_basic']))
        self.pushButton_updateUWB.clicked.connect(lambda: common_data['handler_ui'].pushButton_updateUWB_click(self, common_data['cfg_basic']))
        self.pushButton_uwbModeSet.clicked.connect(lambda: common_data['handler_ui'].pushButton_uwbModeSet_click(self, common_data['cfg_basic']))
        self.pushButton_uwbModeUnSet.clicked.connect(lambda: common_data['handler_ui'].pushButton_uwbModeUnSet_click(self, common_data['cfg_basic']))
        self.pushButton_StartShip.clicked.connect(lambda: common_data['handler_ui'].pushButton_StartShip_click(self, common_data['cfg_basic']))
        self.pushButton_StopShip.clicked.connect(lambda: common_data['handler_ui'].pushButton_StopShip_click(self, common_data['cfg_basic']))
        self.initCfgPage()

    def initCfgPage(self):
        try:
            common_data['cfg_basic'].load_from_file()
        except:
            None
        self.spinBox_UWB1_X.setValue(common_data['cfg_basic'].get('UWB1_pos')[0])
        self.spinBox_UWB1_Y.setValue(common_data['cfg_basic'].get('UWB1_pos')[1])
        self.spinBox_UWB2_X.setValue(common_data['cfg_basic'].get('UWB2_pos')[0])
        self.spinBox_UWB2_Y.setValue(common_data['cfg_basic'].get('UWB2_pos')[1])
        self.spinBox_UWB3_X.setValue(common_data['cfg_basic'].get('UWB3_pos')[0])
        self.spinBox_UWB3_Y.setValue(common_data['cfg_basic'].get('UWB3_pos')[1])

        self.spinBox_PoolLength.setValue(common_data['cfg_basic'].get('poolLength'))
        self.spinBox_PoolWidth.setValue(common_data['cfg_basic'].get('poolWidth'))

        self.spinBox_PID_P.setValue(common_data['cfg_basic'].get('PID1')[0])
        self.spinBox_PID_I.setValue(common_data['cfg_basic'].get('PID1')[1])
        self.spinBox_PID_D.setValue(common_data['cfg_basic'].get('PID1')[2])
        self.spinBox_PID_P_2.setValue(common_data['cfg_basic'].get('PID2')[0])
        self.spinBox_PID_I_2.setValue(common_data['cfg_basic'].get('PID2')[1])
        self.spinBox_PID_D_2.setValue(common_data['cfg_basic'].get('PID2')[2])

    
    def on_config_changed(self, key, value):

        """当配置变化时更新 UI"""
        if key == "poolWidth":
            self.spinBox_PoolWidth.setValue(value)
        elif key == "poolLength":
            self.spinBox_PoolLength.setValue(value)
        
        elif key == "UWB1_pos":
            self.spinBox_UWB1_X.setValue(value[0])
            self.spinBox_UWB1_Y.setValue(value[1])
        elif key == "UWB2_pos":
            self.spinBox_UWB2_X.setValue(value[0])
            self.spinBox_UWB2_Y.setValue(value[1])
        elif key == "UWB3_pos":
            self.spinBox_UWB3_X.setValue(value[0])
            self.spinBox_UWB3_Y.setValue(value[1])
        elif key == "PID1":
            self.spinBox_PID_P.setValue(value[0])
            self.spinBox_PID_I.setValue(value[1])
            self.spinBox_PID_D.setValue(value[2])
        elif key == "PID2":
            self.spinBox_PID_P_2.setValue(value[0])
            self.spinBox_PID_I_2.setValue(value[1])
            self.spinBox_PID_D_2.setValue(value[2])


    def save_config(self):
        filename = 'config.json'
        common_data['cfg_basic'].save_to_file(filename)

    def load_config(self):
        """从文件加载配置"""
        # 打开文件选择对话框
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            "选择配置文件", 
            "", 
            "JSON 文件 (*.json);;所有文件 (*)"
        )
        
        if not file_path:  # 用户取消选择
            return
        
        try:
            common_data['cfg_basic'].load_from_file(file_path)
            print("已加载配置……")        
        except Exception as e:
            QMessageBox.critical(self, '错误', f'加载配置失败: {str(e)}')



common_data['win_main'] = MainWindow()